package com.sofwin.util;

import org.bytedeco.javacv.CanvasFrame;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.FrameGrabber;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.bytedeco.javacv.OpenCVFrameGrabber;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * ClassName: Camer
 * Description: 读取摄像头
 * date: 2021/4/15 11:07 上午
 *
 * @author andyliu
 * @qq 115176513
 * @since JDK 1.8
 */
public class Canvas {
    public static void main(String[] args) throws FrameGrabber.Exception, InterruptedException {
        // 创建opencv抓取器，一般的电脑和移动端的设备中摄像头的默认序号为0，但是不排除其他情况
        OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(0);
        // 开始获取摄像头数据
        grabber.start();
        // 创建一个画布框用于接收本地摄像头的数据
        CanvasFrame canvas = new CanvasFrame("本地摄像头");
        // 设置画布框的关闭选项
        canvas.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // 设置画布框是否处于前端
        canvas.setAlwaysOnTop(true);
        // 死循环用于接收opencv获取的图像数据
        int num=0;
        // 获取当前图像的宽度和高度
        int imageHeight = grabber.grab().imageHeight;
        int imageWidth = grabber.grab().imageWidth;
        int mheight = imageHeight-10;
        int mwidth = imageWidth-200;
        while(true){
            if(!canvas.isDisplayable()){
                // 关闭抓取器
                grabber.close();
                // 程序推出
                System.exit(2);
            }
            // 将抓取中的图像显示到画布框中
            // 帧率   25
            Java2DFrameConverter java2DFrameConverter = new Java2DFrameConverter();
            BufferedImage bufferedImage = java2DFrameConverter.convert(grabber.grabFrame());
            Graphics2D graphics =  bufferedImage.createGraphics();
            // 一下为设置logo
            // 创建字体
            Font font = new Font("宋体",Font.BOLD,50);
            graphics.setColor(Color.green);
            // 设置字体
            graphics.setFont(font);
            graphics.drawString("软赢科技sofwin",100,100);
            // 右侧设置滚屏的弹幕
            graphics.setFont(new Font("隶书",Font.BOLD,20));

             mheight =mheight-10;
             if(mheight<0){
                 mheight=imageHeight-10;
             }
            graphics.setColor(Color.blue);
            graphics.drawString("棒棒棒",mwidth,mheight);
            canvas.showImage(bufferedImage);

            Thread.sleep(50);
        }
    }
}

